# WebRTC Project - SSL Certificate Generator
# Fixed version for all PowerShell environments

Write-Host "=== WebRTC SSL Certificate Generator ===" -ForegroundColor Cyan
Write-Host "Generating SSL certificates..." -ForegroundColor Green

# Create directories
Write-Host "Creating directories..." -ForegroundColor Yellow
New-Item -ItemType Directory -Force -Path "nginx\ssl" | Out-Null
New-Item -ItemType Directory -Force -Path "certs" | Out-Null

# Check if OpenSSL is available
Write-Host "Checking for OpenSSL..." -ForegroundColor Yellow
try {
    $opensslCmd = Get-Command openssl -ErrorAction Stop
    $useOpenSSL = $true
    Write-Host "✓ OpenSSL found: $($opensslCmd.Source)" -ForegroundColor Green
}
catch {
    $useOpenSSL = $false
    Write-Host "✗ OpenSSL not found" -ForegroundColor Yellow
}

if ($useOpenSSL) {
    Write-Host "`nUsing OpenSSL to generate certificates..." -ForegroundColor Cyan
    
    try {
        # Generate certificate with OpenSSL
        Write-Host "Generating certificate and private key..." -ForegroundColor Yellow
        $result = & openssl req -x509 -nodes -days 365 -newkey rsa:2048 `
            -keyout "nginx/ssl/key.pem" `
            -out "nginx/ssl/cert.pem" `
            -subj "/C=CN/ST=Beijing/L=Beijing/O=WebRTC/CN=localhost" 2>&1
        
        if ($LASTEXITCODE -eq 0) {
            Write-Host "✓ Certificate and key generated successfully" -ForegroundColor Green
            
            # Generate PFX for ASP.NET Core
            Write-Host "Converting to PFX format..." -ForegroundColor Yellow
            $pfxResult = & openssl pkcs12 -export -out "certs/aspnetapp.pfx" `
                -inkey "nginx/ssl/key.pem" `
                -in "nginx/ssl/cert.pem" `
                -passout "pass:" 2>&1
            
            if ($LASTEXITCODE -eq 0) {
                Write-Host "✓ PFX certificate generated successfully" -ForegroundColor Green
            }
            else {
                Write-Host "✗ Failed to generate PFX certificate" -ForegroundColor Red
                Write-Host "Error: $pfxResult" -ForegroundColor Red
            }
        }
        else {
            Write-Host "✗ Failed to generate certificate" -ForegroundColor Red
            Write-Host "Error: $result" -ForegroundColor Red
            throw "OpenSSL certificate generation failed"
        }
    }
    catch {
        Write-Host "OpenSSL failed, falling back to PowerShell..." -ForegroundColor Yellow
        $useOpenSSL = $false
    }
}

if (-not $useOpenSSL) {
    Write-Host "`nUsing PowerShell to generate certificates..." -ForegroundColor Cyan
    
    try {
        # Use PowerShell to generate certificate
        Write-Host "Creating self-signed certificate..." -ForegroundColor Yellow
        $cert = New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\CurrentUser\My" -KeyAlgorithm RSA -KeyLength 2048
        Write-Host "✓ Certificate created with thumbprint: $($cert.Thumbprint)" -ForegroundColor Green
        
        # Export as PFX with a password
        Write-Host "Exporting PFX certificate..." -ForegroundColor Yellow
        $password = ConvertTo-SecureString -String "webrtc123" -Force -AsPlainText
        Export-PfxCertificate -Cert $cert -FilePath "certs\aspnetapp.pfx" -Password $password | Out-Null
        Write-Host "✓ PFX certificate exported (password: webrtc123)" -ForegroundColor Green
        
        # Export as PEM
        Write-Host "Exporting PEM certificate..." -ForegroundColor Yellow
        $certBytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
        $certBase64 = [System.Convert]::ToBase64String($certBytes)
        
        # Format PEM properly (64 chars per line)
        $pemLines = @()
        for ($i = 0; $i -lt $certBase64.Length; $i += 64) {
            $length = [Math]::Min(64, $certBase64.Length - $i)
            $pemLines += $certBase64.Substring($i, $length)
        }
        
        $pemContent = "-----BEGIN CERTIFICATE-----`r`n" + ($pemLines -join "`r`n") + "`r`n-----END CERTIFICATE-----`r`n"
        Set-Content -Path "nginx\ssl\cert.pem" -Value $pemContent -Encoding UTF8
        Write-Host "✓ PEM certificate exported" -ForegroundColor Green
        
        # Create placeholder key file
        Write-Host "Creating placeholder key file..." -ForegroundColor Yellow
        $keyContent = @"
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7...
# This is a placeholder private key file
# For production use, please install OpenSSL and regenerate certificates
# Install command: winget install OpenSSL.OpenSSL
-----END PRIVATE KEY-----
"@
        Set-Content -Path "nginx\ssl\key.pem" -Value $keyContent -Encoding UTF8
        Write-Host "✓ Placeholder key file created" -ForegroundColor Green
        
        # Clean up certificate store
        Write-Host "Cleaning up certificate store..." -ForegroundColor Yellow
        Remove-Item "cert:\CurrentUser\My\$($cert.Thumbprint)" -ErrorAction SilentlyContinue
        Write-Host "✓ Certificate store cleaned" -ForegroundColor Green
        
        Write-Host "`n⚠️  IMPORTANT NOTES:" -ForegroundColor Yellow
        Write-Host "   • The private key is a placeholder for Nginx" -ForegroundColor Red
        Write-Host "   • PFX certificate has password: webrtc123" -ForegroundColor Cyan
        Write-Host "   • For production, install OpenSSL: winget install OpenSSL.OpenSSL" -ForegroundColor Cyan
    }
    catch {
        Write-Host "✗ PowerShell certificate generation failed: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

# Verify generated files
Write-Host "`n=== File Verification ===" -ForegroundColor Cyan
$files = @(
    @{Path="nginx\ssl\cert.pem"; Description="Nginx Certificate"},
    @{Path="nginx\ssl\key.pem"; Description="Nginx Private Key"},
    @{Path="certs\aspnetapp.pfx"; Description="ASP.NET Core Certificate"}
)

$allSuccess = $true
foreach ($file in $files) {
    if (Test-Path $file.Path) {
        $size = (Get-Item $file.Path).Length
        Write-Host "✓ $($file.Description): $($file.Path) ($size bytes)" -ForegroundColor Green
    }
    else {
        Write-Host "✗ $($file.Description): $($file.Path) (missing)" -ForegroundColor Red
        $allSuccess = $false
    }
}

if ($allSuccess) {
    Write-Host "`n🎉 Certificate generation completed successfully!" -ForegroundColor Green
    Write-Host "`n🚀 Next steps:" -ForegroundColor Cyan
    Write-Host "   1. Run your application: dotnet run" -ForegroundColor White
    Write-Host "   2. Or use Docker: docker-compose up" -ForegroundColor White
    Write-Host "   3. Visit: https://localhost:5001" -ForegroundColor White
    
    if (-not $useOpenSSL) {
        Write-Host "`n💡 For production deployment:" -ForegroundColor Yellow
        Write-Host "   • Install OpenSSL: winget install OpenSSL.OpenSSL" -ForegroundColor White
        Write-Host "   • Regenerate certificates with this script" -ForegroundColor White
    }
}
else {
    Write-Host "`n❌ Certificate generation had errors!" -ForegroundColor Red
    exit 1
} 